import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Depart } from './depart.entity';
import { Between, Repository } from 'typeorm';
import { UserSys } from 'src/user/userSys.entity';
import * as moment from 'moment';
import { UserService } from 'src/user/user.service';
import { Cron } from '@nestjs/schedule';
import { RoleEnum } from 'src/role/role.enum';

@Injectable()
export class DepartService {
    constructor(
        @InjectRepository(Depart)
        public readonly depart: Repository<Depart>,
        private readonly userService: UserService
    ) { }

    async create(
        user: UserSys,
        time: string,
        reason: string,
        comment: string,
        system = user.system
    ) {
        const target = await this.depart.findOne({
            where: {
                user: {
                    id: user.id
                }
            }
        })
        if (!!target) await this.depart.remove(target)
        const entity = this.depart.create({
            user,
            system,
            time,
            reason,
            comment
        })
        return await this.leave(await this.depart.save(entity))
    }

    public async leave(
        depart: Depart
    ) {
        const date = moment(depart.time);
        const current = moment(Date.now())
        if (date.isSame(current, "day") || current.isAfter(date, "day")) {
            depart.user.system = null;
            depart.user.role = RoleEnum.member
            depart.user.dept = null;
            await this.userService.userSys.save(depart.user);
        }
        return depart
    }

    @Cron("0 0 0 * * *")
    async autoLeave() {
        const start = moment().startOf("day").toDate()
        const end = moment().endOf("day").toDate()
        const result = await this.depart.find({
            where: {
                time: Between(start, end)
            },
            relations: ["user", "user.system", "system"]
        })
        const users = result.map(({ user }) => {
            user.system = null;
            user.dept = null;
            user.role = RoleEnum.member
            return user;
        })
        await this.userService.userSys.save(users);
    }
}
